package com.xxxx.sso.service;

import com.alibaba.fastjson.JSON;
import com.xxxx.api.service.SSOService;
import com.xxxx.api.pojo.Admin;
import com.xxxx.api.utils.Md5Util;
import com.xxxx.api.utils.UUIDUtil;
import com.xxxx.sso.mapper.AdminMapper;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @Author : ymd
 * @Date : 2020/11/2 0002 11:53
 * @Version 1.0
 * @Description : SSO单点登录服务实现
 */
@Service(version = "1.0")
public class SSOServiceImpl implements SSOService {
    @Resource
    private AdminMapper adminMapper;
    @Resource
    private RedisTemplate<String,Object> template;
    @Value("${user.ticket}")
    private String userTicket;
    /**
     * 登录认证方法
     * @param admin
     * @return
     */
    @Override
    public String Login(Admin admin) {
        //验证用户名
        if (StringUtils.isEmpty(admin.getUserName().trim())){
            return null;
        }
        if (StringUtils.isEmpty(admin.getPassword().trim())){
            return null;
        }
        Admin temp = adminMapper.queryByName(admin.getUserName());
        if (null==temp){
            System.out.println("用户名不存在！");
            return null;
        }
        if (!temp.getPassword().equals(Md5Util.encode(admin.getPassword()))){
            System.out.println("用户密码错误");
            return null;
        }
        ValueOperations<String, Object> opsForValue = template.opsForValue();
        String ticket = UUIDUtil.getUUID();
        opsForValue.set(userTicket+":"+ticket, JSON.toJSONString(temp),30, TimeUnit.MINUTES);
        return ticket;
    }

    /**
     * 验证返回用户信息
     * @param info
     * @return
     */
    @Override
    public Admin validate(String ticket) {
        if (StringUtils.isEmpty(ticket)){
            System.out.println("验证信息为空！");
            return null;
        }
        ValueOperations<String, Object> opsForValue = template.opsForValue();
        Object adminJson = opsForValue.get(userTicket + ":" + ticket);
        String adminTemp=adminJson.toString();
        if (StringUtils.isEmpty(adminJson.toString())){
            System.out.println("对应用户不存在");
        }
        Admin admin = JSON.parseObject(adminTemp, Admin.class);
        return admin;
    }

    /**
     * 从redis删除票据
     * @param ticket
     */
    @Override
    public void logout(String ticket) {
        template.delete(userTicket + ":" + ticket);
    }

    /**
     * 提供用户id服务
     * @param userName
     * @return
     */
    @Override
    public Admin queryByName(String userName) {
        return adminMapper.queryByName(userName);
    }
}
